import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_learn_vi/src/bean/bean_day_stat.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/4.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
class MineMyScoreHisRecoderPage extends StatefulWidget {
  final int extractingId;

  const MineMyScoreHisRecoderPage({
    Key key,
    @required this.extractingId,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MineItem2State();
  }
}

class _MineItem2State extends State<MineMyScoreHisRecoderPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  StreamSubscription<String> _streamSubscription;

  //标签页面保活 或者称保持状态
  @override
  bool get wantKeepAlive => true;

  AnimationController _animationController;

  Animation<Offset> _animation;

  bool _loading = true;

  @override
  void initState() {
    super.initState();

    _animationController = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 1200));

    _animation = new Tween(begin: Offset(0, -1), end: Offset(0, 0)).animate(
        CurvedAnimation(
            curve: Curves.fastOutSlowIn, parent: _animationController));
    getTopicHistoryist();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return Scaffold(
      appBar: AppBar(
        title: Text("答题详情"),
      ),
      body: Container(
        padding: EdgeInsets.only(top: 12),
        color: Colors.white,
        child: buildAnimatedSwitcher(),
      ),
    );
  }

  AnimatedSwitcher buildAnimatedSwitcher() {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 400),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },

      //执行动画的子 Widget
      //只有子 Widget 被切换时才会触发动画
      child: buildBody(),
    );
  }

  Widget buildBody() {
    if (_list.length == 0) {
      if (_loading) {
        return Center(child: LoadingWidget());
      }
      return Center(
        child: NoDataWidget(
          text: "暂无数据",
        ),
      );
    }
    return RefreshIndicator(
      onRefresh: () async {
        await getTopicHistoryist();
        return true;
      },
      child: ListView.builder(
        //去除内边距
        padding: EdgeInsets.all(0),
        //列表子Item个数
        itemCount: _list.length,
        //每个子Item的布局构建
        itemBuilder: (BuildContext context, int index) {
          return buildBodyWidget(index);
        },
      ),
    );
  }

  //每个子Item的布局构建
  Widget buildBodyWidget(int index) {
    BeanDayStat beanDayStat = _list[index];

    String options = beanDayStat.options;
    List<Widget> optionWidgetList = [];
    var pareOptions = jsonDecode(options);
    String opStr = "";
    for (int i1 = 0; i1 < pareOptions.length; i1++) {
      opStr += pareOptions[i1];
    }
    if (opStr.length > 0) {
      List stringList = ["A", "B", "C", "D", "E", "F", "G", "H"];
      for (int i = 0; i < pareOptions.length; i++) {
        String index = stringList[i];
        optionWidgetList.add(
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 2),
                height: 14,
                width: 14,
                decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.all(Radius.circular(20))),
                child: Text(
                  index,
                  style: TextStyle(fontSize: 10),
                ),
              ),
              Expanded(
                child: Text(
                  pareOptions[i].replaceAll("<p>", "").replaceAll("<\/p>", ""),
                  style: TextStyle(fontSize: 12),
                ),
              ),
            ],
          ),
        );
      }
    }

    String rightAnswer = beanDayStat.rightAnswer;

    String titleTips = "本题回答正确";
    Color titleTipsColor = Colors.green;
    if (rightAnswer == 'N') {
      titleTips = "本题回答错误";
      titleTipsColor = Colors.red;
    }
    String myAnswer = beanDayStat.myAnswer;
    if (beanDayStat.myAnswer.length == 0) {
      myAnswer = "未答题";
    }

    //水波纹点击事件监听
    return InkWell(
      //手指点击抬起时的回调
      onTap: () {},
      child: Container(
        margin: EdgeInsets.only(bottom: 20),
        padding: EdgeInsets.only(left: 10, right: 10),
        color: Colors.white,
        //线性布局左右排列
        child: Row(
          //主轴方向开始对齐 在这里是左对齐
          mainAxisAlignment: MainAxisAlignment.start,
          //交叉轴上开始对齐 在这里是顶部对齐
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //左侧的图片
            ClipOval(
              child: Container(
                width: 16,
                height: 16,
                alignment: Alignment.center,
                color: Colors.blue,
                child: Text(
                  "${index + 1}",
                  style: TextStyle(color: Colors.white, fontSize: 10),
                ),
              ),
            ),
            SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${beanDayStat.titleText}",
                    style: TextStyle(color: Colors.black, fontSize: 14),
                  ),
                  Wrap(
                    children: [
                      Text(
                        "${titleTips}",
                        style: TextStyle(
                            color: titleTipsColor,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                      Text(
                        "【正确答案是 ",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 14,
                        ),
                      ),
                      Text(
                        "${beanDayStat.answer}】",
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      ),
                      Text(
                        "【你的答案是 ",
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      ),
                      Text(
                        "${myAnswer}】",
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      )
                    ],
                  ),
                  optionWidgetList.length > 0
                      ? Container(
                          margin: EdgeInsets.only(top: 8),
                          padding: EdgeInsets.all(4),
                          decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2))),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                "本题的选项是",
                                style: TextStyle(
                                    color: Colors.black, fontSize: 14),
                              ),
                              SizedBox(height: 10),
                              ...optionWidgetList
                            ],
                          ),
                        )
                      : Container(),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  List<BeanDayStat> _list = [];

  ///查询我的答题记录
  Future<List<BeanDayStat>> getTopicHistoryist() async {
    Map<String, dynamic> monthMap = {
      "extractingId": widget.extractingId,
    };

    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.appQuestionItelList, queryParameters: monthMap);
    _list = [];
    _loading = false;
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data['list'];
      list.forEach((element) {
        _list.add(BeanDayStat.fromMap(element));
      });
      if (mounted) {
        setState(() {});
      }
      return _list;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return _list;
    }
  }
}
